package com.itrip.log.module.handler;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.scheduling.annotation.Scheduled;

import com.itrip.log.core.ReaderBean;
import com.itrip.log.module.db.domain.GCInfo;
import com.itrip.log.module.db.domain.KeyWordAlarm;
import com.itrip.log.util.Util;

/**
 * Function:解析GClog,发送报警<br>
 *
 * Date :2016年2月22日 <br>
 * Author :coder_czp@126.com<br>
 * Copyright (c) 2015,coder_czp@126.com All Rights Reserved.
 */
public class GCLogParserV2 extends AbstractHandler {

	private Map<String, Integer> gcCount = new ConcurrentHashMap<String, Integer>();

	private Map<String, String> emailMap = new ConcurrentHashMap<String, String>();

	private String template = "[%s][%s]秒内发生[%s]次%s,最后一次详情:%s";

	private int period = 60;

	private int throld = 10;

	@Override
	public void handle(ReaderBean bean) {
		String file = bean.getFile();
		String line = bean.getLine();
		String host = bean.getHost();
		String proc = bean.getProc();
		String key = String.format("%s!%s!%s!", host, file, proc);
		for (KeyWordAlarm kw : alarmManager.getGCRules()) {
			String keyword = KeywordParserV2.testLogMatch(file, new StringBuffer(line), kw);
			if (keyword != null) {
				String countKey = key.concat("!").concat(keyword);
				emailMap.put(countKey, kw.getEmailGroup());
				Util.count(gcCount, countKey);
				saveGCInfo(host, proc, keyword);
			}
		}

		for (Entry<String, Integer> entry : gcCount.entrySet()) {
			Integer value = entry.getValue();
			if (value >= throld) {
				String mapKey = entry.getKey();
				String email = emailMap.get(mapKey);
				String[] split = mapKey.split("!");
				String procName = split[2];
				String keyWord = split[3];
				String info = String.format(template, key, period, value, keyWord, line);
				mQueue.addEmailTask(email, procName, new StringBuffer(info), keyWord);
				emailMap.remove(mapKey);
				gcCount.remove(mapKey);
			}
		}
	}

	private void saveGCInfo(String host, String proc, String keyword) {
		GCInfo info = new GCInfo();
		info.setHost(host);
		info.setProc(proc);
		info.setInfo(keyword);
		info.setTime(System.currentTimeMillis());
		dao.save("GCInfo", info);
	}

	@Override
	public boolean match(String file) {
		return file.endsWith("gc.log");
	}

	@Scheduled(cron = "0 0/1 * * * *")
	public void resetGCCount() {
		emailMap.clear();
		gcCount.clear();
	}

}
